package bma.common.langutil.concurrent;

/**
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class Event {

	private boolean m_AutoReset = false;

	private boolean m_BeSign = false;

	protected Event() {
		this(false);
	}

	public Event(boolean bAutoReset) {
		this(false, bAutoReset);
	}

	public Event(boolean initSign, boolean bAutoReset) {
		m_AutoReset = bAutoReset;
		m_BeSign = initSign;
	}

	public static Event createAutoResetEvent() {
		return new Event(true);
	}

	public static Event createManulResetEvent() {
		return new Event(false);
	}

	public void setEvent() {
		setEvent(true);
	}

	public void setEvent(boolean flag) {
		synchronized (this) {
			m_BeSign = flag;
			notifyAll();
		}

		Thread.yield();
	}

	public void resetEvent() {
		setEvent(false);
	}

	public boolean waitEvent(long time) throws InterruptedException {
		synchronized (this) {
			boolean r = m_BeSign;
			if (!r) {
				if (time != 0)
					wait(time);
				r = m_BeSign;
			}
			if (r && m_AutoReset)
				m_BeSign = false;
			return r;
		}
	}

	public boolean checkEvent() {
		return checkEvent(0);
	}

	public boolean checkEvent(long time) {
		try {
			return waitEvent(time);
		} catch (InterruptedException e) {
			throw new ThreadInterruptedException(e);
		}
	}

	public boolean checkAndWait(long time) {
		synchronized (this) {
			if (checkEvent())
				return true;
			return this.checkEvent(time);
		}
	}

	public void clear() {

	}

	@Override
	public String toString() {
		return "Event[" + m_BeSign + "," + m_AutoReset + "]";
	}
}
